package com.wn.class30.cotroller.houtai;

import com.wn.class30.entity.AdminUser;
import com.wn.class30.entity.Business;
import com.wn.class30.service.AdminUserService;
import com.wn.class30.service.BusinessService;
import com.wn.class30.tools.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.Subject;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("/houtai/page/deploy/shopdeploy/")
@Slf4j
public class BusinessController {
    @Resource
    private BusinessService businessService;
    @Resource
    private AdminUserService adminUserService;
    @RequiresPermissions("/houtai/page/deploy/shopdeploy/list")
    @RequestMapping("getlist")
    public Result getOrderlist(){
        return new Result("0","success",null,null);
    }
    /**
     * 根据条件分页查询商家
     * @param page 当前页码
     * @param limit 页显示条数
     * @param businessStatus 商家状态
     * @param businessTel 商家电话
     * @param businessName 商家名称
     * @return
     * @throws Exception
     */


    @RequestMapping("list")
    public Result selectBusiness(Integer page,Integer limit,String businessStatus,String businessTel,String businessName)throws Exception{
        log.info("businessStatus ==================="+businessStatus);
        Map<String,String> map = new HashMap<>();
        map.put("page",String.valueOf((page-1)*limit));
        map.put("limit",String.valueOf(limit));
        map.put("businessStatus",businessStatus);
        map.put("businessTel",businessTel);
        map.put("businessName",businessName);
        Long orderCount = businessService.selectBusinessCount(map);
        Page p = new Page();
        p.setCurrentPage((page-1)*limit);
        p.setTotalSize(orderCount);
        p.setPageSize(limit);
        long pageSize = orderCount % limit == 0? orderCount / limit:orderCount / limit + 1;
        p.setPageSize((int)pageSize);
        List<Business> businesses = businessService.selectBusiness(map);
        return new Result("0","success",p,businesses);
    }

    /**
     *新增商家
     * @param business
     * @return
     * @throws Exception
     */
    @RequiresPermissions("/houtai/page/deploy/shopdeploy/insert")
    @RequestMapping("insert")
    public Result insertBusiness(Business business, HttpServletRequest request)throws Exception{
        if(business != null){
            business.setBusinessStatus(1);
            Integer businessId = businessService.insertBusiness(business);
            //把商家添加到登陆表里面
            AdminUser adminUser = new AdminUser();
            adminUser.setAdminUserName(business.getBusinessName());
            adminUser.setAdminUserPwd(Md5Utils.getMD5("123"));
            adminUser.setAdminUserRoleId(2);
            adminUser.setBusinessId(businessId);
            adminUser.setTel(business.getBusinessTel());
            adminUserService.insertAdminUser(adminUser);
            //给商家生成付款二维码
            String geturl = QrCodeUtil.geturl(request, businessId);
            File file = new File(geturl);
            String filename = file.getName();
            //取出文件名的后缀名
            String suffix = filename.substring(filename.lastIndexOf("."));
            //利用UUID生成一个不重复的文件名，避免文件名重复覆盖掉源文件
            UUID uuid = UUID.randomUUID();
            //组成新的文件名
            String newFileName = uuid+suffix;
            //创建一个输入缓冲流对象
            BufferedInputStream bufferedInputStream = new BufferedInputStream(new FileInputStream(file));
            //把图片上传到七牛云服务器
            QiniuUtil.upload(newFileName,bufferedInputStream);
            //得到存储地址
            String imgPath = QiniuUtil.fullPath(newFileName);
            //更新当前商家的付款二维码地址
            Business newBusiness = businessService.selectBusinessById(businessId);
            //把付款二维码地址存入数据库
            newBusiness.setBusinessQrcode(imgPath);
            businessService.updateBusinessById(newBusiness);
            //删除本地文件
            file.delete();
            return new Result("200","success",null,null);
        }
        return new Result("200","success",null,null);
    }

    /**
     * 修改商家
     * @param business
     * @return
     * @throws Exception
     */
    @RequiresPermissions("/houtai/page/deploy/shopdeploy/update")
    @RequestMapping("update")
    public Result updateBusinessById(Business business)throws Exception{

        if(business != null){
            businessService.updateBusinessById(business);
            AdminUser adminUser = adminUserService.selectAdminUserByBusinessId(business.getBusinessId());
            if(adminUser != null){
                adminUser.setTel(business.getBusinessTel());
                adminUser.setBusinessId(business.getBusinessId());
                Subject subject = SecurityUtils.getSubject();
                AdminUser adminUser1 = (AdminUser) subject.getPrincipal();
                if(adminUser1.getAdminUserId() == 1){
                    adminUser.setAdminUserRoleId(1);
                }else{
                    adminUser.setAdminUserRoleId(2);
                }
                adminUser.setAdminUserName(business.getBusinessName());
                adminUserService.updateAdminUser(adminUser);
                return new Result("200","success",null,null);
            }
        }
        return new Result("200","success",null,null);
    }

    /**
     * 删除商家
     * @param businessIds
     * @return
     * @throws Exception
     */
    @RequiresPermissions("/houtai/page/deploy/shopdeploy/delete")
    @RequestMapping("delete")
    public Result deleteBusinessById(String businessIds)throws Exception{
        if(businessIds != null && !"".equals(businessIds.trim())){
            Integer[] array = StringToArray.getArray(businessIds);
            for (Integer integer : array) {
                businessService.deleteBusinessById(integer);
                adminUserService.deleteAdminUserByBusinessId(integer);
            }
            return new Result("200","success",null,null);
        }
        return new Result("200","success",null,null);
    }


}
